package org.ohuyo.libra.client.master.webapp;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.ohuyo.commons.servlet.ServletUtils;

/**
 * 
 * @author rabbit
 * 
 */
public class LoginFilter implements Filter {


	public void destroy() {
		// NOOP
	}


	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse resp = (HttpServletResponse) response;

			HttpSession s = req.getSession(false);
			boolean isLogin = true;
			if (s == null) {
				isLogin = false;
			} else {
				String userName = (String) s.getAttribute("userName");
				if (userName == null) {
					isLogin = false;
				}
			}
			if (!isLogin) {
				ServletUtils.sendRedirect(resp, "/portal/index.jsp");
				return;
			}
		}
		chain.doFilter(request, response);
	}


	public void init(FilterConfig filterConfig) throws ServletException {
		// NOOP
	}

}
